<?php
include_once dirname(dirname(dirname(dirname(__FILE__)))).'/np/np_string.php';
class nn_cdn_notify
{
	private $sp_id = null;
	private $cp_id = null;
	private $obj_dom = null;
	
	/**
	 * @return the $error_info
	*/
	public function get_error_info()
	{
		return $this->error_info;
	}
	
	/**
	 * @param field_type $error_info
	 */
	private function set_error_info($error_info)
	{
		$this->error_info[] = $error_info;
		return $error_info;
	}
	
	public function __construct($sp_id = null, $cp_id = null)
	{
		$this->sp_id = $sp_id;
		$this->cp_id = $cp_id;
	}
	
	/**
	 * 返回数据数组
	 * @param number $ret
	 * @param string $str_desc 英文描述
	 * @param string $error_info 错误描述
	 * @return multitype:number string
	 * @author liangpan
	 * @date 2015-12-25
	 */
	private function _return_data($ret=1,$str_desc='',$str_desc_en='',$arr_data_info=null)
	{
		return array(
				'ret'=>$ret,
				'reason'=>$str_desc,
				'reason_en'=>$str_desc_en,
				'data_info'=>$arr_data_info,
		);
	}
	
	/**
	 * 生成CDN反馈文件到本地服务器
	 * @param string $content_id CDNid
	 * @param int $ResultCode 状态结果
	 * @param string $Description 错误描述
	 * @param string $video_type 影片类型
	 * @param string $action 行为动作  REGIST 注册 | UPDATE 更新 | DELETE 删除
	 * @return Ambigous <multitype:number, multitype:number string string >
	 * @return object
	 * @date 2015-05-04
	 */
	public function make_cdn_file($info,$ResultCode=-1,$Description ='inner error',$video_type='media',$action='add',$arr_data=null)
	{
	    $str_type_temp = 'Movie';
	    switch ($video_type)
	    {
	        case 'live_media':
	            $str_type_temp='PhysicalChannel';
	            break;
            case 'playbill':
                $str_type_temp='ScheduleRecord';
                break;
	    }
		$this->obj_dom = new DOMDocument("1.0", 'utf-8');
		$obj_adi=$this->make_xml('ADI',null,array('xmlns:xsi'=>"http://www.w3.org/2001/XMLSchema-instance"));
		$obj_reply = $this->make_xml('Reply',null,null,$obj_adi);
		if(isset($arr_data) && is_array($arr_data) && !empty($arr_data))
		{
		    foreach ($arr_data as $val_group)
		    {
		        $str_type_temp = 'Movie';
		        switch ($val_group['nns_type'])
		        {
		            case 'live_media':
		                $str_type_temp='PhysicalChannel';
		                break;
		            case 'playbill':
		                $str_type_temp='ScheduleRecord';
		                break;
		        }
		        $ResultCode = $val_group['nns_state'] = 1 ? 0 : -1;
		        $Description = $val_group['nns_desc'];
		        $ext_url = (isset($val_group['nns_ext_url']) && !empty($val_group['nns_ext_url'])) ? json_encode($val_group['nns_ext_url'],true) : null;
		        $import_id = (isset($ext_url['nns_import_id']) && strlen($ext_url['nns_import_id']) >0) ? $ext_url['nns_import_id'] : $val_group['nns_import_id'];
		        $service_url = (isset($ext_url['nns_service_url']) && strlen($ext_url['nns_service_url']) >0) ? $ext_url['nns_service_url'] : $val_group['nns_service_url'];
		        $obj_resultinfo = $this->make_xml('Resultinfo',null,array('ObjectID'=>$import_id,'ElementType'=>$str_type_temp),$obj_reply);
		        $this->make_xml('Property',$ResultCode,array('Name'=>'ResultCode'),$obj_resultinfo);
		        $this->make_xml('Property',$Description,array('Name'=>'ErrorDescription'),$obj_resultinfo);
		        $this->make_xml('Property','',array('Name'=>'ServiceURL'),$obj_resultinfo);
		    }
		}
		elseif(isset($arr_data) && is_array($arr_data))
		{
			$obj_adi=$this->make_xml('ADI',null,array('xmlns:xsi'=>"http://www.w3.org/2001/XMLSchema-instance"));
			$obj_reply = $this->make_xml('PrefetchStatus',null,null,$obj_adi);
			$this->make_xml('CDNID',$this->sp_id,null,$obj_reply);
			$obj_task_list = $this->make_xml('Tasklist',null,null,$obj_reply);
			$this->make_xml('TaskNum',count($arr_data),null,$obj_task_list);
			foreach ($arr_data as $val_group)
			{
				$ResultCode = $val_group['nns_state'] = 1 ? 0 : -1;
				$ext_url = (isset($val_group['nns_ext_url']) && !empty($val_group['nns_ext_url'])) ? json_encode($val_group['nns_ext_url'],true) : null;
				$import_id = (isset($ext_url['nns_import_id']) && strlen($ext_url['nns_import_id']) >0) ? $ext_url['nns_import_id'] : $val_group['nns_import_id'];
				$this->make_xml('Task',null,array("TaskID"=>$import_id,"Status"=>$ResultCode),$obj_task_list);
			}
		}
		else
		{
		    $ext_url = (isset($info['nns_ext_url']) && !empty($info['nns_ext_url'])) ? json_encode($info['nns_ext_url'],true) : null;
		    $import_id = (isset($ext_url['nns_import_id']) && strlen($ext_url['nns_import_id']) >0) ? $ext_url['nns_import_id'] : $info['nns_import_id'];
		    $service_url = (isset($ext_url['nns_service_url']) && strlen($ext_url['nns_service_url']) >0) ? $ext_url['nns_service_url'] : $info['nns_url'];
    		$obj_resultinfo = $this->make_xml('Resultinfo',null,array('ObjectID'=>$import_id,'ElementType'=>$str_type_temp),$obj_reply);
    		$this->make_xml('Property',$ResultCode,array('Name'=>'ResultCode'),$obj_resultinfo);
    		$this->make_xml('Property',$Description,array('Name'=>'ErrorDescription'),$obj_resultinfo);
    		$this->make_xml('Property',$service_url,array('Name'=>'ServiceURL'),$obj_resultinfo);
		}
		$str_xml_content = $this->obj_dom->saveXML();
		if(strlen($this->cp_id) < 1)
		{
			return $this->_return_data(1,"CP ID为空：".$this->cp_id,'inner error cp empty');
		}
		if(strlen($this->sp_id) < 1)
		{
			return $this->_return_data(1,"SP ID为空：".$this->sp_id,'inner error sp empty');		
		}
		$base_dir = dirname(dirname(dirname(__FILE__))).'/data/cdn';
		$file_name = np_guid_rand();
		$str_date = date("Ymd");
		$file_dir = "/".$str_date.'/'.$this->sp_id.'/'.$this->cp_id.'/'.$video_type.'/'.$action.'/';
		$result_make_dir = $this->make_dir($base_dir.$file_dir);
		if(!$result_make_dir)
		{
			return $this->_return_data(1,"文件路径生成失败".var_export($this->get_error_info(),true),'inner error make dir error');
		}
		$result_make_file = $this->write_file($str_xml_content,$base_dir.$file_dir.$file_name.'.xml');
		if(!$result_make_dir)
		{
			return $this->_return_data(1,"文件生成失败".var_export($this->get_error_info(),true),'inner error make file error');
		}
		return $this->_return_data(0,"success",'success',$file_dir.$file_name.'.xml');
	}


	/**
	 * 生成CDN反馈文件到本地服务器
	 * @param string $content_id CDNid
	 * @param int $ResultCode 状态结果
	 * @param string $Description 错误描述
	 * @param string $video_type 影片类型
	 * @param string $action 行为动作  REGIST 注册 | UPDATE 更新 | DELETE 删除
	 * @return Ambigous <multitype:number, multitype:number string string >
	 * @return object
	 * @date 2015-05-04
	 */
	public function make_unicom_d3_cdn_file($info,$ResultCode=-1,$Description ='inner error',$video_type='media',$action='add',$arr_data=null)
	{
		$this->obj_dom = new DOMDocument("1.0", 'utf-8');
		$obj_reply = $this->make_xml('PrefetchStatus',null,null);
		$this->make_xml('CDNID',$this->sp_id,null,$obj_reply);
		$obj_task_list = $this->make_xml('Tasklist',null,null,$obj_reply);
		if(isset($arr_data) && is_array($arr_data) && !empty($arr_data))
		{
			$this->make_xml('TaskNum',count($arr_data),null,$obj_task_list);
			foreach ($arr_data as $val_group)
			{
				$ResultCode = $val_group['nns_state'] == 1 ? 0 : -1;
				$ext_url = (isset($val_group['nns_ext_url']) && !empty($val_group['nns_ext_url'])) ? json_decode($val_group['nns_ext_url'],true) : null;
				$import_id = (isset($ext_url['nns_import_id']) && strlen($ext_url['nns_import_id']) >0) ? $ext_url['nns_import_id'] : $val_group['nns_import_id'];
				$this->make_xml('Task',null,array("TaskID"=>$import_id,"Status"=>$ResultCode),$obj_task_list);
			}
		}
		else
		{
			$this->make_xml('TaskNum',1,null,$obj_task_list);
			$ext_url = (isset($info['nns_ext_url']) && !empty($info['nns_ext_url'])) ? json_decode($info['nns_ext_url'],true) : null;
			$import_id = (isset($ext_url['nns_import_id']) && strlen($ext_url['nns_import_id']) >0) ? $ext_url['nns_import_id'] : $info['nns_import_id'];
			$this->make_xml('Task',null,array("TaskID"=>$import_id,"Status"=>$ResultCode),$obj_task_list);
		}
		$str_xml_content = $this->obj_dom->saveXML();
		if(strlen($this->cp_id) < 1)
		{
			return $this->_return_data(1,"CP ID为空：".$this->cp_id,'inner error cp empty');
		}
		if(strlen($this->sp_id) < 1)
		{
			return $this->_return_data(1,"SP ID为空：".$this->sp_id,'inner error sp empty');
		}
		$base_dir = dirname(dirname(dirname(__FILE__))).'/data/cdn';
		$file_name = np_guid_rand();
		$str_date = date("Ymd");
		$file_dir = "/".$str_date.'/'.$this->sp_id.'/'.$this->cp_id.'/'.$video_type.'/'.$action.'/';
		$result_make_dir = $this->make_dir($base_dir.$file_dir);
		if(!$result_make_dir)
		{
			return $this->_return_data(1,"文件路径生成失败".var_export($this->get_error_info(),true),'inner error make dir error');
		}
		$result_make_file = $this->write_file($str_xml_content,$base_dir.$file_dir.$file_name.'.xml');
		if(!$result_make_file)
		{
			return $this->_return_data(1,"文件生成失败".var_export($this->get_error_info(),true),'inner error make file error');
		}

		return $this->_return_data(0,"success",'success',$file_dir.$file_name.'.xml');
	}
	
	/**
	 * 组装基础dom对象类
	 * @param string $key 键
	 * @param string $val 值
	 * @param array $arr_attr attr值
	 * @param object $parent 父级对象
	 * @return object
	 * @date 2015-05-04
	 */
	private function make_xml($key, $val = null, $arr_attr = null,$parent=null)
	{
		if(is_null($parent))
		{
			$parent=$this->obj_dom;
		}
		$$key = isset($val) ? $this->obj_dom->createElement($key, $val) : $this->obj_dom->createElement($key);
		if (!empty($arr_attr) && is_array($arr_attr))
		{
			foreach ($arr_attr as $attr_key => $attr_val)
			{
				$domAttribute = $this->obj_dom->createAttribute($attr_key);
				$domAttribute->value = $attr_val;
				$$key->appendChild($domAttribute);
				$this->obj_dom->appendChild($$key);
			}
		}
		$parent->appendChild($$key);
		//unset($dom);
		unset($parent);
		return $$key;
	}
	
	/**
	 * 创建文件路径
	 * @param string $xml 文件内容
	 * @return boolean
	 * @author liangpan
	 * @date 2016-08-24
	 */
	private function make_dir($base_file_dir)
	{
		if (is_dir($base_file_dir))
		{
			return true;
		}
		$result=mkdir($base_file_dir, 0777, true);
		if(!$result)
		{
			$this->set_error_info("创建文件夹失败，路径为：".$base_file_dir);
			return false;
		}
		return true;
	}
	
	/**
	 * 写入文件内容
	 * @param string $xml 文件内容
	 * @return boolean
	 * @author liangpan
	 * @date 2016-08-24
	 */
	private function write_file($xml,$base_file)
	{
		if(strlen($xml) < 1)
		{
			$this->set_error_info("文件内容为空不写入");
			return false;
		}
		$result = file_put_contents($base_file, $xml, LOCK_EX);
		if($result === false)
		{
			$this->set_error_info("写入文件失败，文件为：".$base_file);
			return false;
		}
		return true;
	}
}